<?php
namespace app\crm\model;

use think\Model;
use think\Db;
use think\Cache;


class Saleprogram extends Model
{
	/**
     * 缓存商品销售方案信息
     */
    protected function saleProgramCache ()
    {
		
		$result = Db::name('shop_sale_program')->order("createtime desc")->select();
        // 以ID为键
        foreach ($result as $val) {
            $saleProgram[$val['id']] = $val;
        }
		
        Cache::set('saleProgram', $saleProgram);
    }
	
	 protected function saleProgramTypeCache ()
    {
		$result = Db::name('shop_program_type')->order("id desc")->select();
        // 以ID为键
        foreach ($result as $val) {
            $saleProgramType[$val['id']] = $val;
        }
		
        Cache::set('saleProgramType', $saleProgramType);
    }
	
    /**
     * 添加销售方案
     * @param  array $data 销售方案数据
     * @return json        添加状态
     */
    public function insertSaleProgram()
    {
		$username = $_SESSION["user_info"]["username"];
		$program_name = $_REQUEST["program_name"];
		$description = $_REQUEST["description"];
		$enable = $_REQUEST["enable"];
		$price = $_REQUEST["price"];
		$info = explode(",",$_REQUEST['info']);
		
		foreach($info as $vm){
			$goodInfo[] = explode("-",$vm);
		}
		foreach($goodInfo as $val){
			$goods_info[] = $val[4]."*".$val[1];
		}
		$arrData = array(
			"program_name" => $program_name,
			"createtime" => date("Y-m-d H:i:s"),
			"createname" => $username,
			"enable" => $enable,
			"goods_info" => implode(" / ",$goods_info),
			"price" => $price,
			"type_id" => $_REQUEST["type_id"],
			"description" => $description
		);
		$result = Db::name('shop_sale_program')->insert($arrData);
		$program_id = Db::name('shop_sale_program')->getLastInsID();
		if ($result){
			$sql = "insert into xy_shop_program_goods(goods_name,goods_money,goods_num,price,goods_id,program_id) values";
			$value = "";
			
			foreach($goodInfo as $row){
				$str = "(";
				$str .= "'" .$row[4]. "',";  	 //商品名称
				$str .= "'" .$row[3]. "',";  	 //商品总价格
				$str .= "'" .$row[1]. "',";  	 //商品数量
				$str .= "'" .$row[2]. "',";  	 //商品单价
				$str .= "'" .$row[0]. "',";  	 //商品ID
				$str .= "'" .$program_id. "'";	 //方案id---最后一个不需要","
				
				$str .= ")";
				$value .= empty($value)?"$str":",$str";
			}
			if( $value ){
				$sql .= $value;
				//dump($sql);die;
				$res = Db::execute($sql);
			}
			$this->saleProgramCache();
			echo json_encode(array('success'=>true,'msg'=>'方案添加成功！'));
		} else {
			echo json_encode(array('msg'=>'方案添加失败！'));
		}
    }


    /**
     * 获取商品销售方案列表
     * @param  int $page <页码>
     * @param  int $limit <每页显示条数>
     * @return array <销售方案列表信息>
     */
    public function getsaleProgramData($page,$limit,$where)
    {
        $count = Db::table('xy_shop_sale_program')->where($where)->count();

        // 查询状态为1的用户数据 并且每页显示10条数据
        $dataList = Db::table('xy_shop_sale_program')->order("createtime desc")->where($where)->limit(($page-1)*$limit,$limit)->select();
        $enableArr = array("Y"=>"显示","N"=>"不显示");
		$users = Cache::get('users');
		foreach($dataList as &$val){
			$val["enable"] = $enableArr[$val["enable"]];
			$val["createname"] = $users[$val["createname"]]["cn_name"];
		}
        $rowsList = count($dataList) ? $dataList : false;
        $arrCate["code"] = 0;
        $arrCate["msg"] = '';
        $arrCate["count"] = $count;
        $arrCate["data"] = $rowsList;
        return $arrCate;
    }


    /**
     * 获取单条销售方案
     * @param  string $where 获取条件
     * @return array         销售方案
     */
    public function getSaleProgramInfo ()
    {
		$where = 'id='.$_REQUEST['id'];
        $result = Db::name('shop_sale_program')->where($where)->find();
        return $result;
    }


   /**
	 * 根据id获取销售方案里的商品
	 * @param  [int]  $id        [方案id]
	 * @return [arr]  $arrCate   [方案商品信息]
	 */
	public function getSaleProgramGoods($id)
	{
		$count = Db::name('shop_program_goods')->where("program_id = $id")->count();
        // 查询状态为1的用户数据 并且每页显示10条数据
        $dataList = Db::name('shop_program_goods')->where("program_id = $id")->select();
        $goodsInfo = Cache::get('goodsInfo');
		foreach($dataList as &$val){
			$val["id"] = $val["goods_id"];
			$val["good_name"] = $goodsInfo[$val["goods_id"]]["good_name"];
			$val["good_num"] = $goodsInfo[$val["goods_id"]]["good_num"];
			$val["cat_name"] = $goodsInfo[$val["goods_id"]]["cat_name"];
			$val["simple_description"] = $goodsInfo[$val["goods_id"]]["simple_description"];
		}
        $rowsList = count($dataList) ? $dataList : false;
        $arrCate["code"] = 0;
        $arrCate["msg"] = '';
        $arrCate["count"] = $count;
        $arrCate["data"] = $rowsList;
        return $arrCate;
	}


    /**
     * 获取单个商品的信息
     * @param  [int] $id [商品id]
     * @return [arr]     [商品的信息]
     */
    public function getGoodsArr($id)
    {
        $arrData = Db::name('shop_goods')->where('id',$id)->find();
        return $arrData;
    }


    /**
     * 更新商品信息
     * @param  [int] $id   [商品id]
     * @param  [arr] $data [商品数据]
     */
    public function updateSaleProgram()
    {
		$id = $_REQUEST["program_id"];
		$data = array(
			"program_name" => $_REQUEST["program_name"],
			"enable"	   => $_REQUEST["enable"],
			"description"  => $_REQUEST["description"],
			"price"        => $_REQUEST["price"],
			"type_id"	   => $_REQUEST["type_id"]
		);
        $result = Db::name('shop_sale_program')->where('id', $id)->update($data);
        if ($result){
            $this->saleProgramCache();
			echo json_encode(array('success'=>true,'msg'=>'更新成功！'));
        } else {
            echo json_encode(array('msg'=>'更新失败！'));
        }
    }


    /**
     * 删除销售方案
     * @param  int      $id     [方案id]
     */
    public function delSaleProgram($id)
    {
        $result = Db::name('shop_sale_program')->where('id',$id)->delete();
        if ($result){
			Db::name('shop_program_goods')->where('program_id',$id)->delete();
            $this->saleProgramCache();
			echo json_encode(array('success'=>true,'msg'=>'删除成功！'));
        } else {
            echo json_encode(array('msg'=>'删除失败！'));
        }
    }


    /**
     * 获取商品销售方案分类列表
     * @param  int $page <页码>
     * @param  int $limit <每页显示条数>
     * @return array <销售方案分类列表信息>
     */
    public function saleProgramTypeDataList($page,$limit)
    {
        $count = Db::table('xy_shop_program_type')->count();

        // 查询状态为1的用户数据 并且每页显示10条数据
        $dataList = Db::table('xy_shop_program_type')->order("id asc")->limit(($page-1)*$limit,$limit)->select();
        $enableArr = array("Y"=>"显示","N"=>"不显示");
		$users = Cache::get('users');
		foreach($dataList as &$val){
            $val["enabled"] = $enableArr[$val["enabled"]];
			$val["outbound_enabled"] = $enableArr[$val["outbound_enabled"]];
		}
        $rowsList = count($dataList) ? $dataList : false;
        $arrCate["code"] = 0;
        $arrCate["msg"] = '';
        $arrCate["count"] = $count;
        $arrCate["data"] = $rowsList;
        return $arrCate;
    }
	
	/**
     * 添加销售方案fenlei
     */
	public function insertSaleProgramType()
    {
        $result = Db::name('shop_program_type')->insert($_REQUEST);
		if ($result){
            $this->saleProgramTypeCache();
			echo json_encode(array('success'=>true,'msg'=>'添加成功！'));
        } else {
            echo json_encode(array('msg'=>'添加失败！'));
        }
    }
	
	/**
     * 删除销售方案
     * @param  int      $id     [方案id]
     */
    public function delSaleProgramType($id)
    {
        $result = Db::name('shop_program_type')->where('id',$id)->delete();
        if ($result){
            $this->saleProgramTypeCache();
			echo json_encode(array('success'=>true,'msg'=>'删除成功！'));
        } else {
            echo json_encode(array('msg'=>'删除失败！'));
        }
    }
	
	/**
     * 获得销售方案
     */
	public function getProgramType()
	{
        if ($_REQUEST['task_id']) {
            $dataList = Db::table('xy_shop_program_type')->where("enabled = 'Y' AND outbound_enabled = 'Y'")->select();
        } else {
            $dataList = Db::table('xy_shop_program_type')->where("enabled = 'Y'")->select();
        }
		return $dataList;
		
	}

}